import store from '@/store'
export default class IndexedDB{
    constructor(databaseName,version){
        this.request = window.indexedDB.open(databaseName, version);
        this.db = null
        this.objectStore = null;
        this.num = 0;//未读消息总数
        this.singleArr = []//单个未读消息数组
        this.roompage = false
        this.error()
        this.success()
    }
    /**
     * 打开数据库失败
     */
    error(){
        this.request.onerror = () => {
            console.log('数据库打开报错');
        };
    }
    /**
     * 打开数据库成功
     */
    success(){
        this.request.onsuccess = (event) => {
            this.db = event.target.result;
            console.log('数据库打开成功');
            store.commit('setconnectDb',true)
        };
    }
    /**
     * 判断表是否存在或创建
     * @param {*} tableName 
     * @param {*} key 表的主键
     */
    upgradeneeded(tableName){
        this.request.onupgradeneeded = (event) => {
            this.db = event.target.result;
            console.log(this.db.objectStoreNames.contains(tableName))
            if (!this.db.objectStoreNames.contains(tableName)) {
               this.objectStore = this.db.createObjectStore(tableName, {keyPath:'target_uid'});
              //  this.objectStore.createIndex('user_uid_unqiue','id', {unique: true});
            }   
        }
    }
    /**
     * 新增数据
     * @param {*} tableName    表名
     * @param {*} option 插入表的字段内容
     */
    add(tableName,option) {
        let _this = this;
        var request = this.db.transaction([tableName], 'readwrite')
          .objectStore(tableName)
          .add(option);
      
        request.onsuccess = function (event) {
          // console.log('数据写入成功');
          store.commit('setRecoredmsg',option)
          //每次有新用户和我聊天时就增加一个
          
          let obj ={
            target_uid:option.target_uid,
            num:1,//当前未读数量
          }
          _this.singleArr.push(obj)
          store.commit('setsingledNum',_this.singleArr)
        };
      
        request.onerror = function (event) {
          console.log('数据写入失败');
        }
    }
    /**
     * 读取数据
     * @param {*} tableName 
     * @param {*} targetid 
     */
    read(tableName,target_id,content,way) {
        let _this = this;
        var transaction = this.db.transaction([tableName]);
        var objectStore = transaction.objectStore(tableName);
        var request = objectStore.get(target_id);
        request.onerror = function(event) {
          console.log('事务失败');
        };
       request.onsuccess = function( event) {
           if (request.result) {
            //  console.log('Name: ' + JSON.stringify(request.result));
            let msg = event.target.result
            // console.log(msg)
             if(content){
              DB.update('huahui_chat',target_id,content,way)//发送 监听更新消息
             }else{
              store.commit('setRecoredmsg',msg) //进入页面获取聊天记录
              console.log(_this.singleArr,'======')
              _this.singleArr.forEach( (item,index) => {//清除指定用户未读消息数量
                if(target_id == item.target_uid){
                  _this.num = _this.num - item.num
                  item.num = 0
                  store.commit('setsingledNum',_this.singleArr)
                  store.commit('setunreadNum',_this.num)
                }
              })
             }
           } else {
             console.log('未获得数据记录');
             if(content){
              DB.add('huahui_chat',{target_uid:target_id,list:[content]})
             }
           }  
        };
     }
     /**
      * 遍历数据表格的所有记录
      * @param {*} tableName 
      */
     readAll(tableName,type) {  
        let _this = this;
        let objectStore = this.db.transaction(tableName).objectStore(tableName);
        let dataList = new Array();
        let i = 0;
         objectStore.openCursor().onsuccess = function (event) {

          let cursor = event.target.result;
           if (cursor) {
              dataList[i] = cursor.value;
              //给每个添加未读下标
              // console.log(_this.singleArr,'-----readAll')
              let user=_this.singleArr.find((user) =>{
                  return user.target_uid === dataList[i]['target_uid'];
                })
              // console.log(user)
              if(!user){
                _this.singleArr.push({target_uid:dataList[i]['target_uid'],num:0})
              }else{
                if(type == 'chat'){
                  _this.singleArr.forEach( (item,index) => {//清除指定用户未读消息数量
                    if(item.target_uid == dataList[i]['target_uid']){
                      item.num = 0
                      store.commit('setsingledNum',_this.singleArr)
                    }
                  })
                }
              }
              // console.log(dataList,'dataList')
              store.commit('setAllmsg',dataList)
              // console.log(_this.singleArr)
              i++;
              cursor.continue();
            } else {
              console.log('没有更多数据了！');
            }
            
            // console.log(_this.singleArr,'_this.singleArr')
            
        };
        
      }
    /**
     * 更新数据  
     * 自动更新了主键为id的记录
     * @param {*} tableName 
     * @param {*} option 
     */
    update(tableName,target_id,content,way) {
        let _this = this;
        var transaction = this.db.transaction([tableName], 'readwrite')
        let objectStore = transaction.objectStore(tableName);
        let request = objectStore.get(target_id)

          request.onsuccess = function(event){
            let result = event.target.result;
            result.list.push(content)
            let updateReq = objectStore.put(result);

            updateReq.onsuccess = function(event){
              // console.log('数据更新成功',result);
              store.commit('setRecoredmsg',result)
              if(!way && window.location.pathname != '/chat'){
                _this.num ++ 
                store.commit('setunreadNum',_this.num)
              }
              
              // console.log(_this.singleArr,'------update')  
              // console.log(content,'content')
              
              /**
               * 一下是监听所有消息更新 如存在这个用户未读消息就直接怎加num  否则push
               */
              let user=_this.singleArr.find((user) =>{
                  return target_id === user.target_uid;
              })
              if(!user){
                _this.singleArr.push({target_uid:target_id,num:1})
              }else{
                _this.singleArr.forEach( (item,index) => {//给指定用户增加未读数量
                  // console.log(target_id,item.target_uid)
                  if(target_id == item.target_uid){
                    item.num ++
                    store.commit('setsingledNum',_this.singleArr)
                  }
                })
              }
            }
            updateReq.onerror = function(event){
              console.log('数据更新失败');
            }
          }
    }
    /**
     * 删除数据
     * @param {*} tableName 
     * @param {*} id 
     */
    remove(tableName,id) {
        var request = this.db.transaction([tableName], 'readwrite')
          .objectStore(tableName)
          .delete(id);
      
        request.onsuccess = function (event) {
          // console.log('数据删除成功');
          DB.readAll('huahui_chat')
        };
    }
}   